﻿#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

class Solution
{
public:
    // 210. 课程表 II
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites)
    {
        unordered_map<int, vector<int>> edges;
        vector<int> in(n);
        vector<int> ret;

        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        for (int i = 0; i < n; ++i)
        {
            if (in[i] == 0)
            {
                q.push(i);
                ret.push_back(i);
            }
        }

        while (q.size())
        {
            int t = q.front();
            q.pop();

            for (auto e : edges[t])
            {
                in[e]--;
                if (in[e] == 0)
                {
                    q.push(e);
                    ret.push_back(e);
                }
            }
        }

        if (ret.size() == n)
            return ret;
        else
            return {};
    }
};

int main()
{
    vector<vector<int>> v{ {1,0},{2,0},{3,0},{3,2},{4,3} };
    vector<int> res = Solution().findOrder(5, v);
    for (auto x : res)
        cout << x << " ";
    cout << endl;

    return 0;
}